local InnerMsg = require("core.InnerMsg")
local Util = require("common.Util")
local DrillDB = require("drill.DrillDB")
local MiddleLogic = require("middle.MiddleLogic")
local Lang = require("common.Lang")
local CommonDB = require("common.CommonDB")
local DrillExcel = require("excel.drill")
local Util = require("common.Util")
local DrillLogic = require("drill.DrillLogic")

-- 加入跨服竞技场队列
-- 防守阵容同步
-- 根据战力获取一个相应的阵容
function onJjcPos(fd, msg)
	local drillObj = Util.copyTable(msg.drillObj)
	DrillDB.updateDrillObj(drillObj)
end

function getDifficulty(quJian, diff,config)
	local str1 = ""
	local str2 = ""

	local stradd = ""
	if quJian == 2 then
		stradd = "1"
	end
	if diff == DrillLogic.DIFF_NORMAL then
		str1 = "zdlMin"
		str2 = "zdlMax"
	elseif diff == DrillLogic.DIFF_ELITE then
		str1 = "zdlMinElite"
		str2 = "zdlMaxElite"
	elseif diff ==  DrillLogic.DIFF_INCUBI then
		str1 = "zdlMinIncubi"
		str2 = "zdlMaxIncubi"
	end

	if stradd == "" then
		return config[str1],  config[str2]
	else
		return config[str1..stradd],  config[str2..stradd]
	end
end

-- 请求关卡
function quest(fd, msg)	
	local drillCfg = DrillExcel.drill[msg.drillId]
	if not drillCfg then return end
	
	-- 第一查找	
	local minPer, maxPer = getDifficulty(1, msg.diff, drillCfg)
	local zdlMin = math.ceil(minPer / 10000 * msg.selZdl)
	local zdlMax = math.ceil(maxPer / 10000 * msg.selZdl)		
	local drillObj = DrillDB.randomDrillObj(zdlMin, zdlMax, msg.ninTb)
	if not drillObj then		
		-- 第二次查找
		minPer, maxPer = getDifficulty(2, msg.diff, drillCfg)
	    zdlMin = math.ceil(minPer / 10000 * msg.selZdl)
	    zdlMax = math.ceil(maxPer / 10000 * msg.selZdl)		
		drillObj = DrillDB.randomDrillObj(zdlMin, zdlMax, msg.ninTb)
		if not drillObj then
			drillObj = DrillDB.randomDrillObj(zdlMin, zdlMax, msg.ninTb, true)
			if not drillObj then
                -- 给一个大的区间 取一个阵容
	            zdlMin = 1000000
	            zdlMax = 4000000
                drillObj = DrillDB.randomDrillObj(zdlMin, zdlMax, msg.ninTb, true)
			end
		end
	end

    if not drillObj then
		return MiddleLogic.sendWLBroadcast(fd, msg.uuid, Lang.DRILL_NOT_FING_DRILL)
    end
	
	local msgRet = InnerMsg.wl.WL_DRILL_QUEST	
	msgRet.uuid =  msg.uuid
	msgRet.drillId = msg.drillId
	msgRet.drillObj = drillObj
	InnerMsg.sendMsg(fd, msgRet)
end

 